package com.buta.common.util;


import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.ShutdownHookProcessDestroyer;

public class SystemUtil {
	
	public static String call(String[] command, long timeout) throws IOException,
			InterruptedException {
		StringBuffer cmdBuffer = new StringBuffer();
		for (String c : command) {
			cmdBuffer.append(c);
			cmdBuffer.append(" ");
		}

		return SystemUtil.call(cmdBuffer.toString() , timeout);
	}
	
	public static String call(String cmd, long timeout) throws ExecuteException, IOException, InterruptedException{
		CommandLine command = CommandLine.parse(cmd);


		// Infinite timeout
		ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);

		// Result Handler for executing the process in a Asynch way
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		
		ByteArrayOutputStream  stdout = new ByteArrayOutputStream();
		// Using Std out for the output/error stream
		PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

		// This is used to end the process when the JVM exits
		ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

		// Our main command executor
		DefaultExecutor executor = new DefaultExecutor();

		// Setting the properties
		executor.setStreamHandler(streamHandler);
		executor.setWatchdog(watchDog);
		executor.setProcessDestroyer(processDestroyer);

		// Executing the command
		executor.execute(command, resultHandler);

		// The below section depends on ur need
		// Anything after this will be executed only when the command completes
		// the execution
		resultHandler.waitFor();
		
		//resultHandler.
		
		//System.out.println("finish:" + stdout.toString());
		return stdout.toString();
	}

}
